# -*- coding: utf-8 -*-
from django import template
import datetime

register = template.Library()

class cCalendar(template.Node):
    def __init__(self,year,mon,day):
        self.year = int(year)
        self.mon = int(mon)
        self.day = int(day)
    
    def render(self, context):       
        return createCalendar(self.year,self.mon,self.day)

def calendar_tag(parser, token):
    try:
        tag_name, arg = token.contents.split(None, 1)
    except:
        today = datetime.date.today()
        year,mon,day = today.year,today.month,today.day
    else:
        try:
            year,mon = arg.split(None, 1)
            day = datetime.date.today().day
        except ValueError:
            raise template.TemplateSyntaxError, "%r tag requires year and mon arguments" % tag_name
    
    return cCalendar(year,mon,day)

def createCalendar(year,mon,day):
    import calendar
    now = '%s年%s月%s'%(year,mon,day)
    cstr = '<table summary="日历">\r\n<caption>%s</caption>\r\n'%now
    cstr += '''<thead>\r\n
            <th abbr="星期一" scope="col" title="星期一">一</th>\r\n
            <th abbr="星期二" scope="col" title="星期二">二</th>\r\n
            <th abbr="星期三" scope="col" title="星期三">三</th>\r\n
            <th abbr="星期四" scope="col" title="星期四">四</th>\r\n
            <th abbr="星期五" scope="col" title="星期五">五</th>\r\n
            <th abbr="星期六" scope="col" title="星期六">六</th>\r\n
            <th abbr="星期日" scope="col" title="星期日">日</th>\r\n
            </thead>\r\n'''
    cstr += '<tbody>\r\n'
    for cal in calendar.monthcalendar(year,mon):
        cal2 = '<tr>\r\n'
        for c in cal:
            if c == 0:
                cal2 += '<td>&nbsp;</td>\r\n'
            else:
                if now[-2:] == str(c):
                    cal2 += '<td bgcolor="#C9C9C9">%s</td>\r\n'%c
                else:
                    cal2 += '<td>%s</td>\r\n'%c
        cal2 += '</tr>\r\n'
        cstr += cal2
    cstr += '</tbody>\r\n</table>\r\n'
    return cstr

register.tag('calendar', calendar_tag)
